package indi.zhifa.recipe.bailan.framework.auth.service.impl;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import indi.zhifa.recipe.bailan.framework.auth.entity.po.BaseRoleEntity;
import indi.zhifa.recipe.bailan.framework.auth.entity.vo.BaseDomainVo;
import indi.zhifa.recipe.bailan.framework.auth.property.SecurityConfig;
import indi.zhifa.recipe.bailan.framework.auth.service.IAuthInitService;
import indi.zhifa.recipe.bailan.framework.auth.service.IBaseAuthNodeService;
import indi.zhifa.recipe.bailan.framework.auth.service.IBaseUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Map;

@Component
@Slf4j
@RequiredArgsConstructor
public class AuthInitServiceImpl implements IAuthInitService {

    protected final SecurityConfig mSecurityConfig;
    protected final IBaseUserService mUserService;
    protected final IBaseAuthNodeService mDepartmentService;


    @Override
    public void init() {
        ClassPathResource classPathResource = new ClassPathResource("auth_init.json");
        byte[] configData = null;
        try {
            InputStream inputStream = classPathResource.getInputStream();
            configData = inputStream.readAllBytes();
        } catch (Exception ex) {
            log.error("缺失配置文件 " + "auth_init.json");
            return;
        }
        JSONObject authInitConfig = JSON.parseObject(configData);
        JSONArray defaultRoles = authInitConfig.getJSONArray("defaultRole");
        JSONArray defaultUser = authInitConfig.getJSONArray("defaultUser");
        JSONArray domainConfigs = authInitConfig.getJSONArray("defaultDomains");
        Map<String, BaseRoleEntity> iniRoles = mUserService.initRole(defaultRoles);
        Map<String, BaseDomainVo> iniDomain = mDepartmentService.init(domainConfigs);
        mUserService.initUser(defaultUser);
    }
}
